package com.dx.mes.service.tool.service;

import com.dx.common.table.ppt.Bis_data;
import com.dx.common.table.ppt.Bis_tool;
import com.dx.common.table.ppt.Ret_tool_alt;
import com.dx.mes.common.dao.IBisDataDao;
import com.dx.mes.common.dao.IBisToolDao;
import com.dx.mes.common.dao.IRetToolAltDao;
import com.dx.mes.common.dao.IRetToolStDao;
import com.dx.mes.common.transcoder.util.*;
import com.dx.mes.facade.tool.service.IFtptolalarmService;
import com.dx.mes.facade.tool.tx.Ftptolalarm.FtptolalarmI;
import com.dx.mes.facade.tool.tx.Ftptolalarm.FtptolalarmIA;
import com.dx.mes.facade.tool.tx.Ftptolalarm.FtptolalarmO;
import com.dx.mes.facade.tool.tx.Ftptolalarm.FtptolalarmOA;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import static com.dx.mes.common.bean.def.GenericDef.*;


/**
 * Created on 2017/8/7.
 */
@Service("ftptolalarmService")
public class FtptolalarmService  implements IFtptolalarmService{
    private LogUtils logUtils;
    private static final String TX_NAME = T_FTPTOLALARM;
    private static final String ALARM_OCCURE = "S";
    private static final String ALARM_REST = "R";
    private static final String ALARM_OPI_COMMINT = "O";
    @Autowired
    private IRetToolAltDao retToolAltDao;
    @Autowired
    private IBisToolDao bisToolDao;
    @Autowired
    private IRetToolStDao retToolStDao;
    @Autowired
    private IBisDataDao bisDataDao;
    @Override
    public String subMainProc(String evt_no, String strInMsg) {
        AppContext.clear();
        AppContext.setCurrServiceName(FtptolalarmService.class.getSimpleName());
        AppContext.setCurrEventNumber(evt_no);
        logUtils = new LogUtils(FtptolalarmService.class);
        logUtils.info("[InTrx:" + strInMsg + "]");
        String outMsg = null;
        FtptolalarmO outTrx = new FtptolalarmO();
        outTrx.setTrx_id(TX_NAME);
        outTrx.setType_id(TRX_OUT);
        outTrx.setRtn_code(String.valueOf(RETURN_CODE_SET_ERROR));

        try {
            FtptolalarmI inTrx = JacksonUtil.fromJson(strInMsg,  FtptolalarmI.class);
            char action_flg = inTrx.getAction_flg().charAt(0);
            switch (action_flg) {
	            case ACTION_FLG_QUERY:
	                queryByCondition(inTrx,outTrx);
	                break;
                case ACTION_FLG_ADD:
                	alarmOccureOrRestFnc(inTrx,outTrx);
                    break;
                case ACTION_FLG_DELETE:
                    alarmDeleteFnc(inTrx,outTrx);
                    break;
                case 'I':
                    queryById(inTrx,outTrx);
                    break;
                default:
                    errActionFnc(outTrx);
            }
            if (RETURN_CODE_OK.equals(outTrx.getRtn_code())) {
            	retToolAltDao.flushCurSession();
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } catch (Exception ex) {
            outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
            outTrx.setRtn_mesg(ex.toString());
            ex.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            outMsg = JacksonUtil.toJSONStr(outTrx);
            logUtils.info("[OutTrx:" + outMsg + "]");
        }
        return outMsg;
    }

    /**
     * 查询设备报警信息
     * @param inTrx
     * @param outTrx
     */
    public void queryByCondition(FtptolalarmI inTrx, FtptolalarmO outTrx) {
        FtptolalarmIA iary = inTrx.getIary().get(0);
        String lineIdFk = inTrx.getLine_id_fk();
        String fabIdFk = inTrx.getFab_id_fk();
        String toolIdFk = inTrx.getTool_id_fk();
        String startTime = iary.getStart_timestamp().toString();
        String endTime = iary.getEnd_timestamp().toString();
        String alarmCode = iary.getAlarm_code();
        String alarmDealUsr = iary.getAlarm_deal_usr();
        String alarmLvl = iary.getAlarm_lvl();

        String hql = "FROM Ret_tool_alt where 1=1 and start_timestamp >=" 
        		+ "'" + startTime.substring(0,19)+"'"
                + " and start_timestamp <=" + "'" + endTime.substring(0,19) +"'";
        
        if (!Util.isSpaceCheck(lineIdFk)) {
            hql += " and line_id_fk = '"+lineIdFk+"'";
        }

        if (!StringUtils.isEmpty(fabIdFk)) {
            hql += " and fab_id_fk = '"+fabIdFk+"'";
        }
        
        if(!Util.isSpaceCheck(toolIdFk)){
        	hql += " and tool_id_fk = '"+toolIdFk+"'";
        }
        
        if (!Util.isSpaceCheck(alarmCode)) {
            hql += " and alarm_code = '"+alarmCode+"'";
        }

        if (!Util.isSpaceCheck(alarmDealUsr)) {
            hql += " and alarm_deal_usr = '"+alarmDealUsr+"'";
        }
        if (!Util.isSpaceCheck(alarmLvl)) {
            hql += " and alarm_lvl = '"+alarmLvl+"'";
        }

        List<Ret_tool_alt> retToolAltList = retToolAltDao.find(hql);
        List<FtptolalarmOA> oaryList = new ArrayList<FtptolalarmOA>();
        for (Ret_tool_alt ret_tool_alt:retToolAltList) {
            FtptolalarmOA oary = new FtptolalarmOA();
            oary.setEvt_seq_id(ret_tool_alt.getEvt_seq_id());
            oary.setTool_id_fk(ret_tool_alt.getTool_id_fk());
            oary.setStart_timestamp(ret_tool_alt.getStart_timestamp());
            oary.setEnd_timestamp(ret_tool_alt.getEnd_timestamp());
            oary.setAlarm_code(ret_tool_alt.getAlarm_code());
            oary.setLine_id_fk(ret_tool_alt.getLine_id_fk());
            oary.setFab_id_fk(ret_tool_alt.getFab_id_fk());
            oary.setAlarm_deal_usr(ret_tool_alt.getAlarm_deal_usr());
            oary.setAlarm_lvl(ret_tool_alt.getAlarm_lvl());
            oary.setAlarm_evt_typ(ret_tool_alt.getAlarm_evt_typ());
            oary.setAlarm_dsc(ret_tool_alt.getAlarm_dsc());
            oary.setAlarm_note(ret_tool_alt.getAlarm_note());
            oary.setAlarm_deal_meas(ret_tool_alt.getAlarm_deal_meas());
            oary.setAlarm_deal_result(ret_tool_alt.getAlarm_deal_result());
            oary.setFeat_act_usr(ret_tool_alt.getFeat_act_usr());
            oary.setFeat_action(ret_tool_alt.getFeat_action());
            oaryList.add(oary);
        }
        outTrx.setRtn_code(RETURN_CODE_OK);
        outTrx.setRtn_mesg(RETURN_MESG_OK);
        outTrx.setOary(oaryList);
        outTrx.setTbl_cnt(oaryList.size());
        return;
    }
    
    /**
     * 设备报警信息发生和重置操作
     * @param inTrx
     * @param outTrx
     */
    public void alarmOccureOrRestFnc(FtptolalarmI inTrx, FtptolalarmO outTrx) {

        if(inTrx.getSpeciall_type().equals("pecvd")){
            long lRc = dealPecvdAlarm(inTrx,outTrx);
            if(lRc != _NORMAL){
                outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
                outTrx.setRtn_mesg("pecvd警报处理有误");
                return;
            }
        }else{
            Ret_tool_alt ret_tool_alt = new Ret_tool_alt();
            List<Ret_tool_alt> ret_tool_altList = new ArrayList<Ret_tool_alt>();
            Calendar c = Calendar.getInstance();
            Integer month = c.get(Calendar.MONTH) + 1;
            Integer week = c.get(Calendar.WEEK_OF_YEAR) + 1;
            if(_NO.equals(inTrx.getOpi_ope_flg())){//设备自动上报报警
                if(ALARM_OCCURE.equals(inTrx.getAlarm_evt_typ())){//报警发生
                    for(FtptolalarmIA iary:inTrx.getIary()){
                        ret_tool_alt = new Ret_tool_alt();
                        ret_tool_alt.setEvt_seq_id(GUIDGenerator.javaGUID());
                        ret_tool_alt.setTool_id_fk(inTrx.getTool_id_fk());
                        //设置线别
                        if(Util.isSpaceCheck(inTrx.getLine_id_fk())){
                            //获取设备绑定的线别信息
                            Bis_tool bis_tool = bisToolDao.get(inTrx.getTool_id_fk());
                            if(bis_tool == null){
                                outTrx.setRtn_code(E_BIS_TOOL + E_READ_NOT_FOUND + "");
                                outTrx.setRtn_mesg("未找到设备[" + inTrx.getTool_id_fk() + "]信息");
                                return;
                            }else{
                                ret_tool_alt.setLine_id_fk(bis_tool.getBay_id());
                            }
                        }else{
                            ret_tool_alt.setLine_id_fk(inTrx.getLine_id_fk());
                        }

                        ret_tool_alt.setAlarm_code(iary.getAlarm_code());
                        //月数
                        ret_tool_alt.setAlarm_mfmn(month.toString());
                        //周数
                        ret_tool_alt.setAlarm_mfwk(week.toString());
                        ret_tool_alt.setAlarm_lvl(iary.getAlarm_lvl());
                        ret_tool_alt.setAlarm_dsc(iary.getAlarm_dsc());
                        ret_tool_alt.setAlarm_note(iary.getAlarm_note());
                        ret_tool_alt.setEvt_usr(inTrx.getEvt_user());
                        ret_tool_alt.setEvt_timestamp(Util.getCurrentTimestamp());
                        ret_tool_alt.setAlarm_evt_typ(ALARM_OCCURE);
                        ret_tool_alt.setStart_timestamp(inTrx.getAlarm_time());
                        ret_tool_altList.add(ret_tool_alt);
                    }
                }else if(ALARM_REST.equals(inTrx.getAlarm_evt_typ())){//报警重置
                    for(FtptolalarmIA iary:inTrx.getIary()){
                        ret_tool_altList = retToolAltDao.find("FROM Ret_tool_alt WHERE tool_id_fk='" + inTrx.getTool_id_fk()
                                + "' AND alarm_code='" + iary.getAlarm_code() + "'");
                        for(int i=0; i<ret_tool_altList.size(); i++){
                            ret_tool_altList.get(i).setEnd_timestamp(inTrx.getAlarm_time());
                            ret_tool_altList.get(i).setAlarm_note(iary.getAlarm_note());
                            ret_tool_altList.get(i).setAlarm_deal_usr(iary.getAlarm_deal_usr());
                            ret_tool_altList.get(i).setAlarm_deal_meas(iary.getAlarm_deal_meas());
                            ret_tool_altList.get(i).setAlarm_deal_result(iary.getAlarm_deal_result());
                            ret_tool_altList.get(i).setFeat_action(iary.getFeat_action());
                            ret_tool_altList.get(i).setFeat_act_usr(iary.getFeat_act_usr());
                            ret_tool_altList.get(i).setEvt_usr(inTrx.getEvt_user());
                            ret_tool_altList.get(i).setEvt_timestamp(Util.getCurrentTimestamp());
                            ret_tool_altList.get(i).setAlarm_evt_typ(ALARM_REST);
                            //时间段
                            Long tmp = Util.getDiffMin(ret_tool_altList.get(i).getStart_timestamp(), ret_tool_altList.get(i).getEnd_timestamp());
                            ret_tool_altList.get(i).setTime_period(Integer.valueOf(tmp.toString()));
                        }
                    }
                }
            }else{
                FtptolalarmIA iary = inTrx.getIary().get(0);
                if(Util.isSpaceCheck(inTrx.getEvt_seq_id())){//新增
                    ret_tool_alt = new Ret_tool_alt();
                    ret_tool_alt.setEvt_seq_id(GUIDGenerator.javaGUID());
                    ret_tool_alt.setTool_id_fk(inTrx.getTool_id_fk());
                    ret_tool_alt.setLine_id_fk(inTrx.getLine_id_fk());
                    ret_tool_alt.setFab_id_fk(inTrx.getFab_id_fk());
                    ret_tool_alt.setAlarm_code(iary.getAlarm_code());
                    //月数
                    ret_tool_alt.setAlarm_mfmn(month.toString());
                    //周数
                    ret_tool_alt.setAlarm_mfwk(week.toString());
                    ret_tool_alt.setAlarm_lvl(iary.getAlarm_lvl());
                    ret_tool_alt.setAlarm_dsc(iary.getAlarm_dsc());
                    ret_tool_alt.setAlarm_note(iary.getAlarm_note());
                    ret_tool_alt.setAlarm_deal_usr(iary.getAlarm_deal_usr());
                    ret_tool_alt.setAlarm_deal_meas(iary.getAlarm_deal_meas());
                    ret_tool_alt.setAlarm_deal_result(iary.getAlarm_deal_result());
                    ret_tool_alt.setFeat_action(iary.getFeat_action());
                    ret_tool_alt.setFeat_act_usr(iary.getFeat_act_usr());
                    ret_tool_alt.setEvt_usr(inTrx.getEvt_user());
                    ret_tool_alt.setEvt_timestamp(Util.getCurrentTimestamp());
                    ret_tool_alt.setAlarm_evt_typ(ALARM_OPI_COMMINT);
                    ret_tool_alt.setStart_timestamp(iary.getStart_timestamp());
                    ret_tool_alt.setEnd_timestamp(iary.getEnd_timestamp());
                    //时间段
                    Long tmp = Util.getDiffMin(ret_tool_alt.getStart_timestamp(), ret_tool_alt.getEnd_timestamp());
                    ret_tool_alt.setTime_period(Integer.valueOf(tmp.toString()));
                    ret_tool_altList.add(ret_tool_alt);
                }else{//修改
                    ret_tool_alt = retToolAltDao.get(inTrx.getEvt_seq_id());
                    if(ret_tool_alt == null){
                        outTrx.setRtn_code(E_RET_TOOL_ALT + E_READ_NOT_FOUND + "");
                        outTrx.setRtn_mesg("未找到报警信息");
                        return;
                    }
                    ret_tool_alt.setEnd_timestamp(iary.getEnd_timestamp());
                    ret_tool_alt.setAlarm_lvl(iary.getAlarm_lvl());
                    ret_tool_alt.setAlarm_dsc(iary.getAlarm_dsc());
                    ret_tool_alt.setAlarm_note(iary.getAlarm_note());
                    ret_tool_alt.setAlarm_deal_usr(iary.getAlarm_deal_usr());
                    ret_tool_alt.setAlarm_deal_meas(iary.getAlarm_deal_meas());
                    ret_tool_alt.setAlarm_deal_result(iary.getAlarm_deal_result());
                    ret_tool_alt.setFeat_action(iary.getFeat_action());
                    ret_tool_alt.setFeat_act_usr(iary.getFeat_act_usr());
                    ret_tool_alt.setEvt_usr(inTrx.getEvt_user());
                    ret_tool_alt.setEvt_timestamp(Util.getCurrentTimestamp());
                    ret_tool_alt.setAlarm_evt_typ(ALARM_OPI_COMMINT);
                    //时间段
                    Long tmp = Util.getDiffMin(ret_tool_alt.getStart_timestamp(), ret_tool_alt.getEnd_timestamp());
                    ret_tool_alt.setTime_period(Integer.valueOf(tmp.toString()));
                    ret_tool_altList.add(ret_tool_alt);
                }
            }

            if(!ret_tool_altList.isEmpty()){
                retToolAltDao.saveOrUpdateAll(ret_tool_altList);
            }
        }

        outTrx.setRtn_code(RETURN_CODE_OK);
        outTrx.setRtn_mesg(RETURN_MESG_OK);
        return;
    }

    //pecvd特殊处理警报
    public long dealPecvdAlarm(FtptolalarmI inTrx, FtptolalarmO outTrx){
        long lRc = _NORMAL;
        Ret_tool_alt ret_tool_alt = new Ret_tool_alt();
        List<Ret_tool_alt> ret_tool_altList = new ArrayList<Ret_tool_alt>();
        Calendar c = Calendar.getInstance();
        Integer month = c.get(Calendar.MONTH) + 1;
        Integer week = c.get(Calendar.WEEK_OF_YEAR) + 1;

        for(FtptolalarmIA iary:inTrx.getIary()){
            String toolIdFk = inTrx.getTool_id_fk();
            String alarm_code = iary.getAlarm_code();
            String variable_name = iary.getVariable_Name();
            String mainTool= toolIdFk.split("_")[0];
            String position= toolIdFk.split("_")[1];
            ArrayList<Integer> indexList = testStringIndexOf2(alarm_code);
            String hql1 = "From Bis_data where data_cate = 'PECF' ";
            //[{"tool_id":"PE20_LIFT","variable_Name":"MW08","tool_stat":"111111"}]
            //todo toolId 需改
            if("LIFT".equals(toolIdFk)){//机械手
                hql1 += " and ext_1 ='机械手'";
            }else{//管体
                hql1 += " and ext_1 ='管体'";
            }
            hql1 += " and ext_2 ='" + variable_name +"'";
            List<Bis_data> bisDataList = bisDataDao.find(hql1);
            if(bisDataList != null && bisDataList.size() > 0){
                for(Bis_data bis_data : bisDataList){
                    if(StringUtils.isEmpty(bis_data.getExt_4())){
                        continue;
                    }else{
                        String indexString = bis_data.getExt_3();
                        Integer  indexInteger = Integer.valueOf(indexString);
                        if(indexList.contains(indexInteger)){//上报警报包含当前设定的警报
                            String alarmName = bis_data.getExt_4();

                            ret_tool_alt = new Ret_tool_alt();
                            ret_tool_alt.setEvt_seq_id(GUIDGenerator.javaGUID());
                            ret_tool_alt.setTool_id_fk(toolIdFk);
                            //设置线别
                            if(Util.isSpaceCheck(inTrx.getLine_id_fk())){
                                //获取设备绑定的线别信息
                                Bis_tool bis_tool = bisToolDao.get(inTrx.getTool_id_fk());
                                if(bis_tool == null){
                                    lRc = 11111;
                                    return lRc;
                                }else{
                                    ret_tool_alt.setLine_id_fk(bis_tool.getBay_id());
                                }
                            }else{
                                ret_tool_alt.setLine_id_fk(inTrx.getLine_id_fk());
                            }

                            ret_tool_alt.setAlarm_code(alarmName);
                            //月数
                            ret_tool_alt.setAlarm_mfmn(month.toString());
                            //周数
                            ret_tool_alt.setAlarm_mfwk(week.toString());
                            ret_tool_alt.setAlarm_lvl(iary.getAlarm_lvl());
                            ret_tool_alt.setAlarm_dsc(iary.getAlarm_dsc());
                            ret_tool_alt.setAlarm_note(iary.getAlarm_note());
                            ret_tool_alt.setEvt_usr(inTrx.getEvt_user());
                            ret_tool_alt.setEvt_timestamp(Util.getCurrentTimestamp());
                            ret_tool_alt.setAlarm_evt_typ(ALARM_OCCURE);
                            ret_tool_alt.setStart_timestamp(inTrx.getAlarm_time());
                            ret_tool_altList.add(ret_tool_alt);
                        }
                    }
                }
            }
        }
        if(!ret_tool_altList.isEmpty()){
            retToolAltDao.saveOrUpdateAll(ret_tool_altList);
        }
        return lRc;
    }


    /**
     * 删除报警信息
     */
    public void alarmDeleteFnc(FtptolalarmI inTrx, FtptolalarmO outTrx) {
    	Ret_tool_alt ret_tool_alt = retToolAltDao.get(inTrx.getEvt_seq_id());
    	if(ret_tool_alt != null){
    		retToolAltDao.delete(ret_tool_alt);
    	}
        outTrx.setRtn_code(RETURN_CODE_OK);
        outTrx.setRtn_mesg(RETURN_MESG_OK);
        return;
    }
    
    /**
     * 根据ID获取报警信息
     * @param inTrx
     * @param outTrx
     */
    public void queryById(FtptolalarmI inTrx, FtptolalarmO outTrx){
        Ret_tool_alt ret_tool_alt = retToolAltDao.get(inTrx.getEvt_seq_id());
        if(ret_tool_alt == null){
            outTrx.setRtn_code(E_RET_TOOL_ALT + E_READ_NOT_FOUND + "");
            outTrx.setRtn_mesg("未找到报警信息");
            return;
        }

        List<FtptolalarmOA> oaryList = new ArrayList<FtptolalarmOA>();
        FtptolalarmOA oary = new FtptolalarmOA();
        oary.setEvt_seq_id(ret_tool_alt.getEvt_seq_id());
        oary.setTool_id_fk(ret_tool_alt.getTool_id_fk());
        oary.setStart_timestamp(ret_tool_alt.getStart_timestamp());
        oary.setEnd_timestamp(ret_tool_alt.getEnd_timestamp());
        oary.setAlarm_code(ret_tool_alt.getAlarm_code());
        oary.setFab_id_fk(ret_tool_alt.getFab_id_fk());
        oary.setLine_id_fk(ret_tool_alt.getLine_id_fk());
        oary.setAlarm_deal_usr(ret_tool_alt.getAlarm_deal_usr());
        oary.setAlarm_lvl(ret_tool_alt.getAlarm_lvl());
        oary.setAlarm_evt_typ(ret_tool_alt.getAlarm_evt_typ());
        oary.setAlarm_dsc(ret_tool_alt.getAlarm_dsc());
        oary.setAlarm_note(ret_tool_alt.getAlarm_note());
        oary.setAlarm_deal_meas(ret_tool_alt.getAlarm_deal_meas());
        oary.setAlarm_deal_result(ret_tool_alt.getAlarm_deal_result());
        oary.setFeat_act_usr(ret_tool_alt.getFeat_act_usr());
        oary.setFeat_action(ret_tool_alt.getFeat_action());
        oaryList.add(oary);
        outTrx.setRtn_code(RETURN_CODE_OK);
        outTrx.setRtn_mesg(RETURN_MESG_OK);
        outTrx.setOary(oaryList);
        outTrx.setTbl_cnt(oaryList.size());
        return;
    }
    
    public void errActionFnc(FtptolalarmO outTrx) {
        outTrx.setRtn_code("0000009");
        outTrx.setRtn_mesg("Invalid Action_flg");
    }


    public ArrayList<Integer> testStringIndexOf2(String str){
        String key = "1";
        String reverseStr  = new StringBuffer(str).reverse().toString();
        System.out.println(reverseStr);
        int a = reverseStr.indexOf(key);//*第一个出现的索引位置
        ArrayList<Integer> arrList = new ArrayList<>();
        while (a != -1) {
            System.out.print(a + "\t");
            arrList.add(a);
            a = reverseStr.indexOf(key, a + 1);//*从这个索引往后开始第一个出现的位置
        }
        return arrList;
    }
}
